package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Spu;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author shkstart
 * @create 2020-03-24 14:03
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SpuMapper spuMapper;

    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {

        // 初始化example对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        // 根据name模糊查询，或者根据首字母查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%").orEqualTo("letter", key);
        }

        // 添加分页条件
        PageHelper.startPage(page, rows);

        // 添加排序条件
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + " " + (desc ? "desc" : "asc"));
        }

        List<Brand> brands = brandMapper.selectByExample(example);
        // 包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        // 包装成分页结果集返回
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());

    }
    @Transactional
    public void insertBrand(Brand brand, List<Integer> cids) {
        brandMapper.insertSelective(brand);
        for (Integer cid : cids) {
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        }
    }

    @Transactional
    public void updateBrand(Brand brand, List<Integer> cids) {
        brandMapper.updateByPrimaryKeySelective(brand);
        brandMapper.deleteCategortAndBrandByBid(brand.getId());
        for (Integer cid : cids) {
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        }
    }

    @Transactional
    public void deleteBrand(Long id) {
        brandMapper.deleteByPrimaryKey(id);
        brandMapper.deleteTbCategoryAndBrand(id);
    }

    public List<Brand> queryBrandByCid(Long cid) {
      return   brandMapper.queryBrandByCid(cid);
    }

    public Brand queryBrandByBrandId(Long brandId) {
      return brandMapper.selectByPrimaryKey(brandId);
    }


}
